//-----------------------------------------------------------------------------
//
// @file	Texture.cpp
// @brief	Texture file
// @author	Vinod Melapudi
// @date	20Feb2010
//
//-----------------------------------------------------------------------------

#include "Texture.h"

#include "OpenGLRender.h"


Texture::Texture():
	m_width(0), m_height(0)
{
}

Texture::~Texture()
{
	if ( glIsTexture( m_gl_id ) )		glDeleteTextures( 1, &m_gl_id );
}
//
// @brief	Bind texture
//
void Texture::Bind() const
{
	glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, m_gl_id );	
}


// Load texture from image
bool Texture::Load( const Image& image )
{
	m_width = image.GetWidth();
	m_height = image.GetHeight();

	// Generate & Bind texture
	GLuint texID;
	glGenTextures( 1, &texID );
	glBindTexture( GL_TEXTURE_2D, texID );
	m_gl_id = (unsigned int)texID;

	// Set the parameters for filters, wrapping
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );

	// Generate texture mipmaps
	int numComponents = 3;
	if ( image.GetColorMode() == GL_RGBA || image.GetColorMode() == GL_BGRA )
		numComponents = 4;

	gluBuild2DMipmaps( GL_TEXTURE_2D, numComponents, m_width, m_height, image.GetColorMode(), GL_UNSIGNED_BYTE, image.GetData() );
	//glTexImage2D( GL_TEXTURE_2D, 0, numComponents, m_width, m_height, 0, image.GetColorMode(), GL_UNSIGNED_BYTE, image.GetData() );

	return true;
}

//
// @brief	Load texture from file
//
bool Texture::Load( const char * fileName, IMAGE_TYPE type )
{
	Image img( fileName, type );
	return Load( img );
}